package pl.edu.mimuw.irs.core.model.design.processing;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import pl.edu.mimuw.irs.core.global.UniqueObject;

/**
 * @author Jakub Rauch
 * Created on: 2009-05-07
 */
public class Requirement extends UniqueObject {

	// *** Attributes

	// Set of custom roles that an actor must be capable of acting to meet this requirement.
	private Map<Role, RoleInstance> rolesInstancesMap;
	private String name;
	private Map<Role, RoleInstance> getRolesInstancesMap() {
		if (this.rolesInstancesMap == null) this.rolesInstancesMap = new HashMap<Role, RoleInstance>();
		return this.rolesInstancesMap;
	}
	public void setRolesMap(Map<Role, RoleInstance> rolesMap) {
		this.rolesInstancesMap = rolesMap;
	}
	public Collection<RoleInstance> getRolesInstances() {
		return getRolesInstancesMap().values();
	}
	public void setRoles(Set<RoleInstance> roles) {
		Map<Role, RoleInstance> rolesInstancesMap = getRolesInstancesMap();
		for (RoleInstance role : roles) {
			rolesInstancesMap.put(role.getRole(), role);
		}
	}
	public RoleInstance getRoleInstance(Role role) {
		return getRolesInstancesMap().get(role);
	}
	public void addRoleInstance(RoleInstance roleInstance) {
		getRolesInstancesMap().put(roleInstance.getRole(), roleInstance);
	}
	public void removeRoleInstance(Role role) {
		getRolesInstancesMap().remove(role);
	}
	public String getName() {
		/*if (name == null) TODO : ugly*/  name = createNewName();
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
	// *** Constructors
	
	public Requirement(String name) {
		setRolesMap(new HashMap<Role, RoleInstance>());
		//addRolesInstances(rolesInstances);
		setName(name);
		setId(getPrefixedNewId(getName() + "_"));
	}
	
	public Requirement() {
		this(null);
	}
	
	// *** Methods
	
	private String createNewName() {
		StringBuffer nameBuffer = new StringBuffer();
		nameBuffer.append("Req");
		//if (getRolesInstances().size() > 0) {
		//	nameBuffer.append("[");
			for (RoleInstance instance : getRolesInstances()) {
				nameBuffer.append(instance.toString());
		//		nameBuffer.append(";");
			}
		//	nameBuffer.replace(nameBuffer.lastIndexOf(";"), 
		//			nameBuffer.length(), "]");
		//}
		return nameBuffer.toString();
	}
	
	@Override
	public String toString() {
		return getName();
	}
}
